#define _CRT_SECURE_NO_WARNINGS 1
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode* root) {
        long long ret = 0, cur = -1;
        _sumNumbers(root, cur, ret);
        return ret;
    }
    void _sumNumbers(TreeNode* root, long long cur, long long& ret)
    {
        if (root == nullptr) return;
        if (cur == -1) cur = root->val;
        else cur = cur * 10 + root->val;
        if (root->left == nullptr && root->right == nullptr)
        {
            ret += cur;
            return;
        }

        _sumNumbers(root->left, cur, ret);
        _sumNumbers(root->right, cur, ret);
    }
};